/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.instancemanager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javolution.util.FastMap;

import jmmos.MMODatabaseFactory;
import jmmos.gameserver.datatables.GuildTable;
import jmmos.gameserver.model.MMOGuild;
import jmmos.gameserver.model.MMOObject;
import jmmos.gameserver.model.StatsSet;
import jmmos.gameserver.model.entity.Auction;
import jmmos.gameserver.model.entity.GuildHall;
import jmmos.gameserver.model.entity.guildhall.AuctionableHall;
import jmmos.gameserver.model.entity.guildhall.SiegableHall;
import jmmos.gameserver.model.zone.type.MMOGuildHallZone;

/**
 * @author Steuf
 */
public final class GuildHallManager
{
	protected static final Logger _log = Logger.getLogger(GuildHallManager.class.getName());
	
	private final Map<Integer, AuctionableHall> _guildHall;
	private final Map<Integer, AuctionableHall> _freeGuildHall;
	private final Map<Integer, AuctionableHall> _allAuctionableGuildHalls;
	private static Map<Integer, GuildHall> _allGuildHalls = new FastMap<>();
	private boolean _loaded = false;
	
	public boolean loaded()
	{
		return _loaded;
	}
	
	protected GuildHallManager()
	{
		_guildHall = new FastMap<>();
		_freeGuildHall = new FastMap<>();
		_allAuctionableGuildHalls = new FastMap<>();
		load();
	}
	
	/** Load All Guild Hall */
	private final void load()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			Statement s = con.createStatement();
			ResultSet rs = s.executeQuery("SELECT * FROM guildhall ORDER BY id"))
		{
			int id, ownerId, lease;
			while (rs.next())
			{
				StatsSet set = new StatsSet();
				
				id = rs.getInt("id");
				ownerId = rs.getInt("ownerId");
				lease = rs.getInt("lease");
				
				set.set("id", id);
				set.set("name", rs.getString("name"));
				set.set("ownerId", ownerId);
				set.set("lease", lease);
				set.set("desc", rs.getString("desc"));
				set.set("location", rs.getString("location"));
				set.set("paidUntil", rs.getLong("paidUntil"));
				set.set("grade", rs.getInt("Grade"));
				set.set("paid", rs.getBoolean("paid"));
				AuctionableHall ch = new AuctionableHall(set);
				_allAuctionableGuildHalls.put(id, ch);
				addGuildHall(ch);
				
				if (ch.getOwnerId() > 0)
				{
					_guildHall.put(id, ch);
					continue;
				}
				_freeGuildHall.put(id, ch);
				
				Auction auc = AuctionManager.getInstance().getAuction(id);
				if ((auc == null) && (lease > 0))
				{
					AuctionManager.getInstance().initNPC(id);
				}
			}
			_log.info(getClass().getSimpleName() + ": Loaded: " + getGuildHalls().size() + " guild halls");
			_log.info(getClass().getSimpleName() + ": Loaded: " + getFreeGuildHalls().size() + " free guild halls");
			_loaded = true;
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: GuildHallManager.load(): " + e.getMessage(), e);
		}
	}
	
	public static final Map<Integer, GuildHall> getAllGuildHalls()
	{
		return _allGuildHalls;
	}
	
	/**
	 * @return all FreeGuildHalls
	 */
	public final Map<Integer, AuctionableHall> getFreeGuildHalls()
	{
		return _freeGuildHall;
	}
	
	/**
	 * @return all GuildHalls that have owner
	 */
	public final Map<Integer, AuctionableHall> getGuildHalls()
	{
		return _guildHall;
	}
	
	/**
	 * @return all GuildHalls
	 */
	public final Map<Integer, AuctionableHall> getAllAuctionableGuildHalls()
	{
		return _allAuctionableGuildHalls;
	}
	
	public static final void addGuildHall(GuildHall hall)
	{
		_allGuildHalls.put(hall.getId(), hall);
	}
	
	/**
	 * @param chId
	 * @return true is free GuildHall
	 */
	public final boolean isFree(int chId)
	{
		if (_freeGuildHall.containsKey(chId))
		{
			return true;
		}
		return false;
	}
	
	/**
	 * Free a GuildHall
	 * @param chId
	 */
	public final synchronized void setFree(int chId)
	{
		_freeGuildHall.put(chId, _guildHall.get(chId));
		GuildTable.getInstance().getGuild(_freeGuildHall.get(chId).getOwnerId()).setHideoutId(0);
		_freeGuildHall.get(chId).free();
		_guildHall.remove(chId);
	}
	
	/**
	 * Set GuildHallOwner
	 * @param chId
	 * @param guild
	 */
	public final synchronized void setOwner(int chId, MMOGuild guild)
	{
		if (!_guildHall.containsKey(chId))
		{
			_guildHall.put(chId, _freeGuildHall.get(chId));
			_freeGuildHall.remove(chId);
		}
		else
		{
			_guildHall.get(chId).free();
		}
		GuildTable.getInstance().getGuild(guild.getGuildId()).setHideoutId(chId);
		_guildHall.get(chId).setOwner(guild);
	}
	
	/**
	 * @param guildHallId
	 * @return Guild Hall by Id
	 */
	public final GuildHall getGuildHallById(int guildHallId)
	{
		return _allGuildHalls.get(guildHallId);
	}
	
	public final AuctionableHall getAuctionableHallById(int guildHallId)
	{
		return _allAuctionableGuildHalls.get(guildHallId);
	}
	
	/**
	 * @param x
	 * @param y
	 * @param z
	 * @return Guild Hall by x,y,z
	 */
	public final GuildHall getGuildHall(int x, int y, int z)
	{
		for (GuildHall temp : getAllGuildHalls().values())
		{
			if (temp.checkIfInZone(x, y, z))
			{
				return temp;
			}
		}
		return null;
	}
	
	public final GuildHall getGuildHall(MMOObject activeObject)
	{
		return getGuildHall(activeObject.getX(), activeObject.getY(), activeObject.getZ());
	}
	
	public final AuctionableHall getNearbyGuildHall(int x, int y, int maxDist)
	{
		MMOGuildHallZone zone = null;
		
		for (Map.Entry<Integer, AuctionableHall> ch : _guildHall.entrySet())
		{
			zone = ch.getValue().getZone();
			if ((zone != null) && (zone.getDistanceToZone(x, y) < maxDist))
			{
				return ch.getValue();
			}
		}
		for (Map.Entry<Integer, AuctionableHall> ch : _freeGuildHall.entrySet())
		{
			zone = ch.getValue().getZone();
			if ((zone != null) && (zone.getDistanceToZone(x, y) < maxDist))
			{
				return ch.getValue();
			}
		}
		return null;
	}
	
	public final GuildHall getNearbyAbstractHall(int x, int y, int maxDist)
	{
		MMOGuildHallZone zone = null;
		for (Map.Entry<Integer, GuildHall> ch : _allGuildHalls.entrySet())
		{
			zone = ch.getValue().getZone();
			if ((zone != null) && (zone.getDistanceToZone(x, y) < maxDist))
			{
				return ch.getValue();
			}
		}
		return null;
	}
	
	/**
	 * @param guild
	 * @return Guild Hall by Owner
	 */
	public final AuctionableHall getGuildHallByOwner(MMOGuild guild)
	{
		for (Map.Entry<Integer, AuctionableHall> ch : _guildHall.entrySet())
		{
			if (guild.getGuildId() == ch.getValue().getOwnerId())
			{
				return ch.getValue();
			}
		}
		return null;
	}
	
	public final GuildHall getAbstractHallByOwner(MMOGuild guild)
	{
		// Separate loops to avoid iterating over free guild halls
		for (Map.Entry<Integer, AuctionableHall> ch : _guildHall.entrySet())
		{
			if (guild.getGuildId() == ch.getValue().getOwnerId())
			{
				return ch.getValue();
			}
		}
		for (Map.Entry<Integer, SiegableHall> ch : CHSiegeManager.getInstance().getConquerableHalls().entrySet())
		{
			if (guild.getGuildId() == ch.getValue().getOwnerId())
			{
				return ch.getValue();
			}
		}
		return null;
	}
	
	public static GuildHallManager getInstance()
	{
		return SingletonHolder._instance;
	}
	
	private static class SingletonHolder
	{
		protected static final GuildHallManager _instance = new GuildHallManager();
	}
}